/*  *******************************************************************************
 *      Copyright:  (C) 2025 ZYT
 *                  All rights reserved.
 *
 *       Filename:  ds18b20.c
 *    Description:  This file get temperature.
 *               
 *        Version:  1.0.0(28/03/25)
 *         Author:  Zhang yuting <zhangyuting@163.com>
 *      ChangeLog:  1, Release initial version on "28/03/25 17:53:01"
 *                                   
 *********************************************************************************/

#include "ds18b20.h"

int get_temperature(float *temper)
{
	DIR                   *dirp = NULL;
	char                   w1_path[64] = "/sys/bus/w1/devices/"; 
	struct dirent         *direntp = NULL;
	int                    found = 0;
	char                   chip_sn[32];
	char                   buf[128];
	char                  *ptr = NULL;
	int                    fd = -1;

	dirp = opendir(w1_path);
	if(!dirp)
	{
		dbg_printf("open folder %s failure: %s\n", w1_path, strerror(errno));
		return -1;
	}

	while( NULL != (direntp = readdir(dirp)) )
	{
		if(strstr(direntp->d_name, "28-"))
		{
			strncpy(chip_sn, direntp->d_name, sizeof(chip_sn));
			found = 1;
		}
	}

	closedir(dirp);

	if( !found )
	{
		dbg_printf("can not fond ds18b20 chipset\n");
		return -2;
	}

	strncat(w1_path, chip_sn, sizeof(w1_path)-strlen(w1_path));
	strncat(w1_path, "/w1_slave", sizeof(w1_path)-strlen(w1_path));

	if( (fd = open(w1_path, O_RDONLY)) < 0 )
	{
		dbg_printf("open file failure: %s\n", strerror(errno));
		close(fd);
		return -3;
	}

	memset(buf, 0, sizeof(buf));

	if( read(fd, buf, sizeof(buf)) < 0)
	{
		dbg_printf("read data from fd[%d] failure: %s\n", fd, strerror(errno));
		close(fd);
		return -4;
	}

	ptr = strstr(buf, "t=");
	if( !ptr )
	{
		dbg_printf("can not find t= string\n");
		return -5;
	}

	ptr += 2;

	*temper = atof(ptr)/1000;
	dbg_printf("temperature: %f\n", *temper);

	close(fd);

	return 0;
}


